<!-- by 7527189 2 0 -->
<template>
  <a-row :gutter="24">
    <a-col :md="8">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper">
          <!-- 搜索区域 -->
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="18">
              <a-col :md="24">
                <a-form-item label="项目" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select placeholder="请选择项目" @select="onProjectSelected" allowClear>
                    <a-select-option v-for="project in projectList" :key="project.id" :title="project.name" :value="project.id">
                      {{ project.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="18" style="margin: 10px auto;">
              <a-col :md="24">
                <a-button @click="handleProjectQuoteAdd" type="primary" icon="plus" block>新增报价单</a-button>
              </a-col>
            </a-row>
            <a-row>
              <a-col :md="24">
                <a-list size="small" bordered :data-source="quoteProjectList">
                  <a-list-item slot="renderItem" slot-scope="item, index" >
                    <a slot="actions" @click="handleProjectQuoteClick(item)">查看</a>
                    <a-dropdown slot="actions">
                      <a-menu slot="overlay">
                        <a-menu-item key="edit" @click="handleProjectQuoteEdit(item,index)">编辑</a-menu-item>
                        <a-menu-item key="copy" @click="handleProjectQuoteCopy(item,index)">复制</a-menu-item>
                        <a-menu-item key="export" @click="handleProjectQuoteExport(item,index)">导出</a-menu-item>
                        <a-menu-item key="remove" @click="handleProjectQuoteDelete(item,index)">删除</a-menu-item>
                      </a-menu>
                      <a-button>操作<a-icon type="down" /> </a-button>
                    </a-dropdown>
                    <a-list-item-meta :description="item.remark" >
                      <a slot="title" >{{ item.name }}</a>
                    </a-list-item-meta>
                  </a-list-item>
                  <div slot="header">
                    {{'项目: '+selectedProject.name}}
                  </div>
                </a-list>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </a-card>
    </a-col>

    <a-col :md="16" >

      <a-card v-if="this.selectedQuoteProject.id !== ''" :style="cardStyle" :bordered="false" :title="'报价单名称: '+this.selectedQuoteProject.name">
        <a slot="extra" href="#" @click="handleAdd">添加材料</a>
        <a-divider type="vertical" slot="extra"/>
        <a slot="extra" href="#" @click="handleTemplateSelect">导入模板</a>
        <!-- 操作按钮区域 -->
<!--        <div class="table-operator"  style="margin-top: 5px">-->
<!--          <a-button @click="handleAdd" type="primary" icon="plus">添加材料</a-button>-->
<!--        </div>-->
        <!-- 操作按钮区域 -->
        <div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="defColumns"
            :dataSource="dataSource"
            :scroll="scroll"
            :loading="loading"
            @change="handleTableChange">
                <span slot="action" slot-scope="text, record">
                  <a @click="handleQuoteProjectEdit(record)">编辑</a>
                  <a-divider type="vertical" />
                  <a-popconfirm title="确定删除吗?" @confirm="() => handleQuoteProjectDelete(record.id)">
                    <a>删除</a>
                  </a-popconfirm>
                </span>
          </a-table>
        </div>

        <!-- table区域-end -->




      </a-card>

      <a-card v-if="this.selectedQuoteProject.id === ''">
        <a-empty>
          <span slot="description"> 请先选择报价单 </span>
        </a-empty>
      </a-card>
    </a-col>

    <quote-project-modal ref="quoteProjectModal" @ok="refresh"></quote-project-modal>
    <j-select-material-modal ref="materialModal" @ok="onSelectMaterial"></j-select-material-modal>
    <quote-project-item-modal ref="quoteProjectItemModal" @ok="queryQuoteProjectItems"></quote-project-item-modal>
    <quote-template-select-modal ref="quoteTemplateSelectModal" @ok="onSelectQuoteTemplate"></quote-template-select-modal>
  </a-row>

</template>
<script>
import ImportFileModal from '@/components/tools/ImportFileModal'
import { findBySelectProject, queryQuoteCategoryTreeList } from '@/api/api'
import { getMpListShort, getNowFormatStr } from '@/utils/util'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import JEllipsis from '@/components/jeecg/JEllipsis'
import JDate from '@/components/jeecg/JDate'
import Vue from 'vue'
import { deleteAction, downFile, getAction, postAction } from '@api/manage'
import QuoteTemplateItemModal from '@views/quote/modules/QuoteTemplateItemModal.vue'
import JSelectMaterialModal from '@comp/jeecgbiz/modal/JSelectMaterialModal.vue'
import MaterialModal from '@views/material/modules/MaterialModal.vue'
import QuoteProjectModal from '@views/quote/modules/QuoteProjectModal.vue'
import QuoteProjectItemModal from '@views/quote/modules/QuoteProjectItemModal.vue'
import QuoteTemplateSelectModal from '@views/quote/modules/QuoteTemplateSelectModal.vue'

export default {
  name: "ProjectQuote",
  mixins:[JeecgListMixin],
  components: {
    QuoteTemplateSelectModal,
    QuoteProjectItemModal,
    QuoteProjectModal,
    MaterialModal,
    JSelectMaterialModal,
    QuoteTemplateItemModal,
    ImportFileModal,
    JEllipsis,
    JDate
  },
  data () {
    return {
      projectList:[],
      selectedProject:{'name':''},
      quoteProjectList:[],
      selectedQuoteProject:{id:'', name:''},
      subsystemList:[],
      activeSubsystemKey:'',
      newTabIndex: 0,
      model: {},
      labelCol: {
        span: 6
      },
      wrapperCol: {
        span: 18,
        offset: 1
      },
      // 查询条件
      queryParam: {
      },
      // 实际表头
      columns:[],
      // 初始化设置的表头
      settingColumns:['fullBarCode','mBarCode','name','mfrs','standard','model','color','categoryName','materialOther','unit', 'stock',
        'otherField1','caizhi','biaozhun','lianjie','paoguangdu','mopian','changdu','otherField2','otherField3','standard',
        'purchaseDecimal','commodityDecimal','wholesaleDecimal','discountRate','taxRate','lowDecimal','enabled','enableSerialNumber','enableBatchNumber','action'],
      // 默认的列
      defColumns: [
        {
          title: '操作',
          dataIndex: 'action',
          align:"center",
          width: 100,
          scopedSlots: { customRender: 'action' },
        },
        // {title: '图片', dataIndex: 'pic', width: 65, scopedSlots: { customRender: 'customPic' }},
        // {title: '子系统', dataIndex: 'subSystem', width: 80},
        {title: '名称', dataIndex: 'materialInfo.name', width: 120, scopedSlots: { customRender: 'customName' } },
        {title: '类别', dataIndex: 'materialInfo.categoryName', width: 100 },
        {title: '数量', dataIndex: 'count', width: 80},
        {title: '单位', dataIndex: 'materialInfo.unit', width: 50 ,
          customRender:function (t,r,index) {
            if (r) {
              let name = t?t:r.unitName
              if(r.sku) {
                return name + '[SKU]';
              } else {
                return name;
              }
            }
          }
        },
        {title: '单价（元）', dataIndex: 'materialInfo.wholesaleDecimal', width: 100},
        // {title: '编码', dataIndex: 'materialInfo.fullBarCode', width: 80},
        // {title: '条码', dataIndex: 'materialInfo.mBarCode', width: 80},
        // {title: '制造商', dataIndex: 'materialInfo.mfrs', width: 120 },
        { title: '规格型号', dataIndex: 'materialInfo.model', width: 120 },
        { title: '尺寸', dataIndex: 'materialInfo.otherField1', width: 80 },
        { title: '材质', dataIndex: 'materialInfo.caizhi' , width: 80},
        { title: '标准', dataIndex: 'materialInfo.biaozhun', width: 80 },
        { title: '连接形式', dataIndex: 'materialInfo.lianjie', width: 80 },
        { title: '抛光要求', dataIndex: 'materialInfo.paoguangdu', width: 80 },
        { title: '密封形式', dataIndex: 'materialInfo.mopian' , width: 80},
        { title: '长度', dataIndex: 'materialInfo.changdu' , width: 80},
        { title: '温度', dataIndex: 'materialInfo.otherField2', width: 80 },
        { title: '压力', dataIndex: 'materialInfo.otherField3' , width: 80},
        { title: '其他技术参数', dataIndex: 'materialInfo.standard', width: 120 },
        // {title: '型号', dataIndex: 'model', width: 120},
        // {title: '其他技术参数', dataIndex: 'standard', width: 120},
        // {title: '颜色', dataIndex: 'color', width: 70 },
        // {title: '扩展信息', dataIndex: 'materialOther', width: 100 },

        // {title: '库存', dataIndex: 'materialInfo.stock', width: 50,
        //   scopedSlots: { customRender: 'customRenderStock' }
        // },
        // {title: '面价', dataIndex: 'wholesaleDecimal', width: 80},
        // {title: '采购单价', dataIndex: 'purchaseDecimal', width: 80},
        // {title: '成本价', dataIndex: 'lowDecimal', width: 80},
        // {title: '仓位货架', dataIndex: 'position', width: 80},
        {title: '备注', dataIndex: 'materialInfo.remark', width: 80},
        {title: '状态', dataIndex: 'enabled', align: "center", width: 60,
          scopedSlots: { customRender: 'customRenderEnabled' }
        }
      ],
      url: {
        list: "/quote/template/item/list?quoteTemplateId="+this.quoteTemplateId,
        delete: "/quote/project/item/delete",
        add: "/quote/template/item/add",
      }
    }
  },
  created() {
    this.model = Object.assign({}, {});
    // this.initColumnsSetting()
    // this.loadQuoteTemplateCategoryTreeData();
    this.queryProjectSelectList();
  },
  computed: {
  },
  methods: {
    queryProjectSelectList(){
      let that = this;
      findBySelectProject().then(res=>{
        if(res) {
          that.projectList = res;
        }
      });
    },
    onProjectSelected(projectId){
      for (let i = 0; i < this.projectList.length; i++) {
        if ( projectId === this.projectList[i].id ) {
          this.selectedProject = this.projectList[i];
        }
      }
      this.queryQuoteProjectList(projectId)
    },
    queryQuoteProjectList(projectId){
      let that = this;
      getAction('/quote/project/list',{'projectId':projectId}).then(res => {
        if(res) {
          that.quoteProjectList = res.data.list
        }
      })
    },
    handleProjectQuoteClick(item){
      this.selectedQuoteProject = item ;
      this.queryQuoteProjectItems();
    },
    handleProjectQuoteAdd(){
      this.$refs.quoteProjectModal.title = '新增报价单:'+this.selectedProject.name;
      this.$refs.quoteProjectModal.add(this.selectedProject);
    },
    handleProjectQuoteEdit (item, index) {
      this.selectedQuoteProject = item ;
      this.$refs.quoteProjectModal.title = '修改报价单:'+this.selectedProject.name;
      this.$refs.quoteProjectModal.edit(item);
    },
    handleProjectQuoteCopy (item, index) {
      this.selectedQuoteProject = item ;
      let that = this;
      this.$confirm({
        title: '确认复制',
        content: '确定要复制报价单： ' + item.name + ' 吗?',
        onOk: function () {
          postAction('/quote/project/copy', {id: item.id}).then((res) => {
            if (res.code === 200) {
              that.$message.success(res.data.message)
              that.refresh()
            } else {
              that.$message.warning(res.data.message)
            }
          })
        }
      })
    },
    handleProjectQuoteExport (item, index) {
      this.selectedQuoteProject = item ;
      let that = this;
      this.$confirm({
        title: '导出报价单',
        content: '确定要导出报价单： ' + item.name + ' 吗?',
        onOk: function () {
          let fileName = '报价单_'+item.name;
          downFile('/quote/project/export', {quoteProjectId: item.id}).then((data) => {
            if (!data) {
              this.$message.warning("文件下载失败")
              return
            }
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
              window.navigator.msSaveBlob(new Blob([data],{type: 'application/vnd.ms-excel'}), fileName+'.xls')
            }else{
              let url = window.URL.createObjectURL(new Blob([data],{type: 'application/vnd.ms-excel'}))
              let link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              link.setAttribute('download', fileName + '_' + getNowFormatStr()+'.xls')
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link); //下载完成移除元素
              window.URL.revokeObjectURL(url); //释放掉blob对象
            }
          })
        }
      })
    },
    handleProjectQuoteDelete (item, index) {
      this.selectedQuoteProject = item ;
      let that = this;
      this.$confirm({
        title: '确认删除',
        content: '确定要删除报价单： ' + item.name + ' 吗?',
        onOk: function () {
          postAction('/quote/project/delete', {id: item.id}).then((res) => {
            if (res.code === 200) {
              that.$message.success(res.data.message)
              that.refresh()
            } else {
              that.$message.warning(res.data.message)
            }
          })
        }
      })
    },
    handleQuoteProjectEdit: function (record)  {
      this.$refs.quoteProjectItemModal.edit(record);
      this.$refs.quoteProjectItemModal.title = "调整数量："+record.materialInfo.name;
      this.$refs.quoteProjectItemModal.disableSubmit = false;
    },
    handleQuoteProjectDelete: function (id) {
      if(!this.url.delete){
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      postAction("/quote/project/item/delete", {id: id}).then((res) => {
        if(res.code === 200){
          this.queryQuoteProjectItems();
        } else {
          that.$message.warning(res.data.message);
        }
      });
    },
    handleAdd: function () {
      if ( this.selectedQuoteTemplateId === ''){
        this.$message.error("请先选择要添加材料的报价单模板")
      }else{
        this.$refs.materialModal.showModal('1')
      }
    },
    queryQuoteProjectItems(){
      this.loading = true;
      return new Promise((resolve, reject) => {
        getAction('/quote/project/item/list', {quoteProjectId:this.selectedQuoteProject.id})
          .then(res => {
            this.loading = false;
            // 更新数据
            this.dataSource = res.data.list;
            resolve(); // 数据加载完成
          })
          .catch(err => {
            reject(err);
          });
      });
    },
    onSelectMaterial(selectMaterialRows, selectMaterialIds){
      // console.log(selectMaterialRows)
      if ( selectMaterialRows.length > 0 ){
        let that = this;
        let params = {
          materialId:selectMaterialRows[0].id,
          quoteProjectId:this.selectedQuoteProject.id
        }
        postAction('/quote/project/item/add',params)
          .then(res=>{
            that.queryQuoteProjectItems();
          })
      }

    },
    handleTemplateSelect(){
      this.$refs.quoteTemplateSelectModal.showModal(this.selectedQuoteProject)
    },
    onSelectQuoteTemplate(quoteTemplateId){
      console.log(quoteTemplateId);
      var that = this;
      var params = {
        quoteTemplateId: quoteTemplateId,
        quoteProjectId: this.selectedQuoteProject.id
      }
      postAction("/quote/project/item/import", params).then((res) => {
        if(res.code === 200){
          that.queryQuoteProjectItems();
        } else {
          that.$message.warning(res.data.message);
        }
      });
    },
    refresh() {
      // 显示加载状态
      this.loading = true;
      this.dataSource = []; // 清空现有数据
      this.selectedQuoteProject = {'id':''}
      // 调用查询方法，并在成功后更新 dataSource
      this.queryQuoteProjectList(this.selectedProject.id);
      this.queryQuoteProjectItems();
      this.loading = false;
    },
    // onTabEdit(targetKey, action){
    //   this[action](targetKey);
    // },
    add() {
      const panes = this.panes;
      const activeKey = `newTab${this.newTabIndex++}`;
      panes.push({ title: 'New Tab', content: 'Content of new Tab', key: activeKey });
      this.panes = panes;
      this.activeKey = activeKey;
    },
    remove(targetKey) {
      let activeKey = this.activeKey;
      let lastIndex;
      this.panes.forEach((pane, i) => {
        if (pane.key === targetKey) {
          lastIndex = i - 1;
        }
      });
      const panes = this.panes.filter(pane => pane.key !== targetKey);
      if (panes.length && activeKey === targetKey) {
        if (lastIndex >= 0) {
          activeKey = panes[lastIndex].key;
        } else {
          activeKey = panes[0].key;
        }
      }
      this.panes = panes;
      this.activeKey = activeKey;
    },
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
<style>
.item-img {
  cursor:pointer;
  position: static;
  display: block;
  width: 100%;
  height: 100%;
  object-fit: cover;
}
</style>